package wmh.day01092.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static java.sql.DriverManager.getConnection;

public class BaseDao {
    //定义了driver url username，password 静态实例
    protected static String driver;
    protected static String url;
    protected static String username;
    protected static String password;
    //Connection数据库连接对象
    protected Connection conn;
    //PreparedStatement 预编译传输实例对象
    protected PreparedStatement pstmt;
    //ResultSet 查询结果实例对象
    protected ResultSet rs;

    //1.建立数据库连接
    public Connection getConn() {
        //获取driver。。。。对应值
        driver = ConfigManager.getInstance().getProperty("orcl.driver");
        url = ConfigManager.getInstance().getProperty("orcl.url");
        username = ConfigManager.getInstance().getProperty("orcl.username");
        password = ConfigManager.getInstance().getProperty("orcl.password");
        try {
            //1.加载数据库驱动
            Class.forName(driver);
            conn = getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //2.关闭数据库连接
    public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
            if (rs != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    //3.定义公共的查询方法
    public ResultSet executeQuery(String sql, Object... params) {

        try {
            conn = getConn();
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
             return rs;
    }

    //4.定义公共的增删改方法
    public int executeUpdate(String sql,Object...params){
        //定义一个变量，用来接受受影响的行数
        int result = 0;
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i <params.length ; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            result = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return  result;
    }
    public static void main(String[] args) {
        BaseDao bd = new BaseDao();
        System.out.println(bd);
    }
}